import {
  Button,
  Divider,
  Form,
  FormItem,
  InputNumber,
  message,
  notification,
  Radio,
  RadioGroup,
  RangePicker,
  Select,
  SelectOption,
  Space,
  Spin,
  Textarea
} from 'ant-design-vue'
import { omit } from 'lodash-es'
import moment from 'moment'
import { computed, defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { couponApi, marketingApi } from '@/apis'
import { ProTable, ProTableProps, ProTableRef } from '@/components/ProTable'
import { useBack } from '@/hooks'
import { isValueEmpty } from '@/utils'
import SelectYxGoodsWithSku from '@/views/marketing/yxGoodsManage/hook/selectYxGoodsWithSku'

import styles from './index.module.css'

export default defineComponent({
  props: {
    isEdit: { type: Boolean, default: false }
  },
  setup(props) {
    const loading = ref(false)
    const selectGoodsRef = ref({} as any)
    const formModel = ref({
      source: 1,
      exchangeActivity: undefined,
      exchangePrice: undefined,
      exchangeStock: 0,
      price: undefined,
      goodsName: '',
      point: undefined,
      goodsId: undefined,
      sort: undefined,
      exchangeLimit: undefined,
      serviceDesc: undefined,
      itemCommandList: [],
      date: [],
      goodsUserStar: 0
    })

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: false,
      options: {
        border: true,
        align: 'center',

        columns: [
          {
            title: '规格名称',
            field: 'goodsSpecName'
          },
          {
            title: '商品货号',
            field: 'erpSpecNo'
          },
          {
            title: '可兑库存',
            field: 'mobile',
            slots: {
              default: 'stockInput'
            }
          },

          {
            title: '市场价',
            field: 'mobile',
            slots: {
              default: 'marketPriceInput'
            }
          },
          {
            title: '兑换价格',
            minWidth: 200,
            field: 'reason',
            slots: {
              default: 'priceInput'
            }
          }
        ],

        proxyConfig: {
          ajax: {
            query: async ({ page }) => {
              return formModel.value.itemCommandList
            }
          }
        }
      }
    } as ProTableProps)

    const sourceOptions = ref([
      // {
      //   label: '优惠券',
      //   value: 0
      // },
      {
        label: '实物',
        value: 1
      }
    ])
    const activityOptions = ref<any[]>([])

    const route = useRoute()

    const id = computed(() => Number(route.query.id))
    const memberList = [
      { label: '注册粉丝', value: 0 },
      { label: '推广者', value: 1 },
      { label: '黑优推广者', value: 2 },
      { label: '好物推荐官', value: 4 }
    ]

    const { handleCancel } = useBack('refreshExchangeCommodity')

    async function handleSubmit() {
      if (formModel.value.source == 0) {
        if (isValueEmpty(formModel.value.exchangeActivity)) {
          message.error('请选择优惠卷')
          return
        }
        if (isValueEmpty(formModel.value.price)) {
          message.error('请输入市场价')
          return
        }
        if (
          isValueEmpty(formModel.value.exchangePrice) ||
          isValueEmpty(formModel.value.point)
        ) {
          message.error('请输入兑换价格')
          return
        }
      } else {
        if (isValueEmpty(formModel.value.goodsId)) {
          message.error('请选择商品')
          return
        }
      }

      if (isValueEmpty(formModel.value.sort)) {
        message.error('请输入排序')
        return
      }
      if (isValueEmpty(formModel.value.exchangeLimit)) {
        message.error('请输入兑换件数')
        return
      }
      if (formModel.value.date.length == 0) {
        message.error('请选择兑换时间')
        return
      }
      try {
        loading.value = true
        const data = {
          ...omit(formModel.value, ['date']),
          exchangeStartTime: moment(formModel.value.date[0]).format('x'),
          exchangeEndTime: moment(formModel.value.date[1]).format('x')
        }

        id.value
          ? await marketingApi.updateExchangeCommodityDetail(data)
          : await marketingApi.createExchangeCommodity(data)
        message.success((id.value ? '编辑' : '新建') + '兑换商品成功')
        handleCancel()
      } finally {
        loading.value = false
      }
    }

    async function init() {
      try {
        loading.value = true
        const res = await couponApi.getExchangeList()
        activityOptions.value = res.map(v => ({
          label: v.name,
          value: v.id,
          stock: v.stock
        }))

        if (props.isEdit) {
          const res = await marketingApi.getExchangeCommodityDetail(id.value)

          // 当关联的优惠券被删除时需要置空
          if (
            activityOptions.value.findIndex(
              v => v.value === res.exchangeActivity
            ) === -1
          ) {
            res.exchangeActivity = undefined as any
          }

          Object.assign(
            formModel.value,
            omit(res, ['exchangeStartTime', 'exchangeEndTime']),
            {
              date: [
                moment(res.exchangeStartTime, 'x'),
                moment(res.exchangeEndTime, 'x')
              ]
            }
          )
          //获取优惠券最新库存
          if (formModel.value.exchangeActivity) {
            onCouponChange(formModel.value.exchangeActivity)
          }
          tableRef.value.refresh()
        }
      } finally {
        loading.value = false
      }
    }

    //来源更改
    function onSourceChange() {
      formModel.value.exchangeStock = 0
      formModel.value.exchangeActivity = undefined
    }

    //优惠券更改
    function onCouponChange(item) {
      formModel.value.exchangeStock = activityOptions.value.find(val => {
        return val.value == item
      }).stock
    }

    //商品更改
    function onGoodsClick() {
      selectGoodsRef.value.show()
    }

    //商品选中
    function onGoodsSelect(item) {
      console.log(item)
      formModel.value.goodsName = item.name
      formModel.value.goodsId = item.id
      formModel.value.itemCommandList = item.skus.map(item => {
        return {
          goodsSpecName: item.name,
          specId: item.id,
          ...item
        }
      })
      tableRef.value.refresh()
    }

    onMounted(() => {
      init()
    })

    return {
      loading,
      formModel,
      sourceOptions,
      activityOptions,
      selectGoodsRef,
      onSourceChange,
      handleCancel,
      handleSubmit,
      onCouponChange,
      onGoodsClick,
      onGoodsSelect,
      tableConfig,
      tableRef,
      memberList
    }
  },
  render() {
    return (
      <div class={styles.view}>
        <Spin spinning={this.loading}>
          <Form labelCol={{ span: 4 }} wrapperCol={{ span: 12 }}>
            <FormItem required label="商品来源">
              <RadioGroup
                v-model:value={this.formModel.source}
                onChange={this.onSourceChange}
              >
                {this.sourceOptions.map(v => (
                  <Radio value={v.value}>{v.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>

            <div v-show={this.formModel.source == 0}>
              <FormItem required label="优惠券">
                <Select
                  style={{ width: '350px' }}
                  v-model:value={this.formModel.exchangeActivity}
                  placeholder="请选择优惠券"
                  onChange={this.onCouponChange}
                >
                  {this.activityOptions.map(v => (
                    <SelectOption value={v.value}>{v.label}</SelectOption>
                  ))}
                </Select>
              </FormItem>
              <FormItem required label="可兑库存">
                <InputNumber
                  disabled
                  min={0}
                  v-model:value={this.formModel.exchangeStock}
                  class={styles.numberInput}
                />
              </FormItem>
              <FormItem required label="市场价">
                <InputNumber
                  precision={2}
                  min={0}
                  v-model:value={this.formModel.price}
                  class={styles.numberInput}
                />
              </FormItem>
              <FormItem required label="兑换价格">
                <Space>
                  <InputNumber
                    precision={2}
                    min={0}
                    v-model:value={this.formModel.exchangePrice}
                    class={styles.numberInput}
                  />
                  {'元 +'}
                  <InputNumber
                    precision={0}
                    min={0}
                    v-model:value={this.formModel.point}
                    class={styles.numberInput}
                  />
                  {'积分'}
                </Space>
              </FormItem>
            </div>
            <div v-show={this.formModel.source == 1}>
              <FormItem required label="商品名称">
                <Select
                  style={{ width: '350px' }}
                  open={false}
                  value={this.formModel.goodsName}
                  placeholder="请选择商品"
                  onClick={this.onGoodsClick}
                ></Select>
                <FormItem
                  label=" "
                  colon={false}
                  v-show={this.formModel.goodsName}
                >
                  <ProTable
                    style={{ width: '800px' }}
                    ref="tableRef"
                    {...this.tableConfig}
                    v-slots={{
                      stockInput: ({ row }) => {
                        return (
                          <InputNumber
                            maxlength={6}
                            min={0}
                            max={Number(row.stock) < 0 ? 0 : Number(row.stock)}
                            v-model:value={row.exchangeStock}
                            precision={0}
                          ></InputNumber>
                        )
                      },
                      marketPriceInput: ({ row }) => {
                        return (
                          <InputNumber
                            precision={2}
                            min={0}
                            v-model:value={row.marketPrice}
                            class={styles.numberInput}
                          />
                        )
                      },
                      priceInput: ({ row }) => {
                        return (
                          <Space>
                            <InputNumber
                              precision={2}
                              min={0}
                              v-model:value={row.exchangePrice}
                              class={styles.numberInput}
                            />
                            {'元 +'}
                            <InputNumber
                              maxlength={5}
                              min={0}
                              precision={0}
                              v-model:value={row.point}
                              class={styles.numberInput}
                            />
                            {'积分'}
                          </Space>
                        )
                      }
                    }}
                  />
                </FormItem>
              </FormItem>
            </div>
            <FormItem label="排序" required>
              <InputNumber
                precision={0}
                min={0}
                v-model:value={this.formModel.sort}
                class={styles.numberInput}
              />
            </FormItem>
            <FormItem label="最低可兑会员" required>
              <Select
                style={{ width: '350px' }}
                placeholder="请选择最低可兑会员"
                v-model:value={this.formModel.goodsUserStar}
                options={this.memberList}
                allowClear={true}
              />
            </FormItem>
            <FormItem required label="限兑件数">
              <InputNumber
                precision={0}
                min={0}
                v-model:value={this.formModel.exchangeLimit}
                class={styles.numberInput}
              />
              <span class={styles.desc}>
                限制每人可兑换该商品件数，0为不限制
              </span>
            </FormItem>
            <FormItem required label="兑换时间">
              <RangePicker
                v-model:value={this.formModel.date}
                showTime={{
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('23:59:59', 'HH:mm:ss')
                  ]
                }}
                separator={'至'}
              />
            </FormItem>
            <FormItem label="服务说明">
              <Textarea
                style={{ width: '350px' }}
                v-model:value={this.formModel.serviceDesc}
                rows={3}
                maxlength={40}
                showCount
              ></Textarea>
            </FormItem>
            <Divider />
            <FormItem class={styles.formBtns} wrapperCol={{ span: 10 }}>
              <Space>
                <Button onClick={this.handleCancel}>取消</Button>
                <Button type="primary" onClick={this.handleSubmit}>
                  确定
                </Button>
              </Space>
            </FormItem>
          </Form>
        </Spin>
        <SelectYxGoodsWithSku
          ref="selectGoodsRef"
          onSelect={this.onGoodsSelect}
        />
      </div>
    )
  }
})
